package com.nehc.nettyserver.netty;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nehc.nettyserver.common.model.Message;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 认证处理器
 * 处理用户认证
 * 
 * @author NEHC
 */
@Slf4j
@Sharable
public class AuthHandler extends ChannelInboundHandlerAdapter {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            String content = frame.text();
            
            try {
                JsonNode jsonNode = objectMapper.readTree(content);
                
                // 检查是否是认证消息
                if (jsonNode.has("type") && "AUTH".equals(jsonNode.get("type").asText())) {
                    log.debug("收到认证消息: {}", content);
                    
                    // 消息会被MessageHandler进一步处理，这里只是记录日志
                    // 如果需要，可以在这里进行额外的认证前处理
                }
            } catch (Exception e) {
                log.error("解析消息失败: {}", e.getMessage());
            }
        }
        
        // 继续传递消息给下一个处理器
        ctx.fireChannelRead(msg);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("认证处理器异常", cause);
        ctx.close();
    }
} 